import { defineStore } from "pinia";
import usePermissionStore from './permission.ts'
import router from "../../router";
import userInfoData from './userInfo.ts'

interface loginParams {
    username: string;
    password: string;
    remember: boolean;
}

const useUserStore = defineStore('user', {
    state: () => {
        return {
            userInfo: {}
        }
    },
    actions: {
        async login(params: loginParams): void {
            const permissionStore = usePermissionStore()
            if (params.username === 'admin' && params.password === '000000') {
                console.log('登录成功')
                permissionStore.setPermissionCodeList(userInfoData.permission)
                userInfoData.remember = params.remember
                const loginInfo = {
                    username: userInfoData.name,
                    password: params.password,
                    remember: params.remember,
                }
                if (params.remember) {
                    localStorage.setItem('loginInfo', JSON.stringify(loginInfo))
                }
                localStorage.setItem('userInfo', JSON.stringify(userInfoData))
                localStorage.setItem('token', userInfoData.token)
                await permissionStore.addRoutes()
                // const routes = await permissionStore.getAsyncRoutes()
                // console.log(routes);
                // console.log(router);
                // for (const i in routes) {
                //     console.log(routes[i]);
                //     router.addRoute(routes[i])
                // }
                // console.log(router.hasRoute('404'));
                // console.log(router.options.routes);
                location.reload()
                // router.replace('/404')
            } else {
                console.error('登录失败')
            }
        },
        getUserInfo(): any {
            return localStorage.getItem('userInfo')
        }
    }
})

export default useUserStore